package com.auto.api.core.type.classtomap;

import com.auto.api.core.constants.MappingConstants;
import com.auto.api.core.entity.ClassToMapContext;
import com.auto.api.core.entity.ProcessProp;
import com.auto.api.core.entity.PropertyContext;
import com.auto.api.core.type.TypeFactory;
import com.auto.api.core.type.defaultvalue.ValueTypeHandler;
import com.auto.api.core.util.BeanUtil;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @program:
 * @description: 类型转换接口
 * @author: liangshf
 * @create: 2020-09-24
 */
public class ClassToParamColumnMapHandler extends AbstractClassToMapHandler {

    @Override
    public ProcessProp<ClassToMapContext> getProcessProp(ClassToMapContext context, PropertyContext propertyContext) {
        PropertyDescriptor prop = propertyContext.getProp();
        String propertyName = prop.getName();
        String attrKey;
        if (context.getParentPropertyName() == MappingConstants.EMPTY_STRING) {
            attrKey = propertyName;
        } else {
            attrKey = propertyName + MappingConstants.LINE + context.getParentPropertyName() + propertyName;
        }
        return new ProcessProp(propertyContext.getJudgePropType(), context, propertyContext, attrKey, null);
    }

    @Override
    public void processProp(ProcessProp<ClassToMapContext> processProp) {
        PropertyDescriptor prop = processProp.getPropertyContext().getProp();
        //多个继承泛型替换
        ValueTypeHandler typeHandler = TypeFactory.getTypeHandler(processProp.getPropType());
        if (typeHandler != null) {
            if (processProp.getPropertyContext().isCollectionType()) {
                //默认使用集合
                processProp.getContext().getResult().put(processProp.getAttrKey(), Arrays.asList(0));
                return;
            }
            processProp.getContext().getResult().put(processProp.getAttrKey(), typeHandler.getTypeDefaultValue());
        } else {
            Map<String, Object> columnMap = getResult(new ClassToMapContext(processProp.getPropertyContext().isObjParse() ? processProp.getPropertyContext().getGenPropResType() : processProp.getPropertyContext().getPropResType()));
            if (processProp.getPropertyContext().isCollectionType()) {
                //默认使用集合
                List list = new ArrayList();
                list.add(columnMap);
                processProp.getContext().getResult().put(processProp.getAttrKey(), list);
                processProp.getContext().getResult().put(prop.getName(), BeanUtil.getApiJsonArray(processProp.getContext().getClazz(), prop, columnMap));
                return;
            }
            processProp.getContext().getResult().put(processProp.getAttrKey(), columnMap);
        }
    }
}
